import React, { useState, useEffect, useMemo, useCallback } from 'react';
import { ServerMetric } from '../types';
import ReactECharts from 'echarts-for-react';
import { PieChart, Activity } from 'lucide-react';

interface DataVisualizationProps {
  servers: ServerMetric[];
}

interface ChartData {
  timestamps: string[];
  cpuData: number[];
  memoryData: number[];
  networkInData: number[];
  networkOutData: number[];
}

export const DataVisualization: React.FC<DataVisualizationProps> = ({ servers }) => {
  const [viewMode, setViewMode] = useState<'timeline' | 'distribution'>('timeline');
  const [selectedDimension, setSelectedDimension] = useState<'server' | 'region' | 'service'>('server');
  const [timeRange, setTimeRange] = useState(5);
  const [chartData, setChartData] = useState<ChartData>({
    timestamps: [],
    cpuData: [],
    memoryData: [],
    networkInData: [],
    networkOutData: []
  });

  const generateChartData = useCallback(() => {
    const now = Date.now();
    const timestamps = [];
    const cpuData = [];
    const memoryData = [];
    const networkInData = [];
    const networkOutData = [];

    for (let i = timeRange - 1; i >= 0; i--) {
      const time = new Date(now - i * 60000);
      timestamps.push(time.toLocaleTimeString());

      const avgCpu = servers.reduce((sum, s) => sum + s.cpu, 0) / servers.length;
      const avgMemory = servers.reduce((sum, s) => sum + s.memory, 0) / servers.length;
      const avgNetworkIn = servers.reduce((sum, s) => sum + s.networkIn, 0) / servers.length;
      const avgNetworkOut = servers.reduce((sum, s) => sum + s.networkOut, 0) / servers.length;

      cpuData.push(avgCpu + (Math.random() - 0.5) * 10);
      memoryData.push(avgMemory + (Math.random() - 0.5) * 10);
      networkInData.push(avgNetworkIn + (Math.random() - 0.5) * 100);
      networkOutData.push(avgNetworkOut + (Math.random() - 0.5) * 100);
    }

    return {
      timestamps,
      cpuData,
      memoryData,
      networkInData,
      networkOutData
    };
  }, [servers, timeRange]);

  useEffect(() => {
    const interval = setInterval(() => {
      setChartData(generateChartData());
    }, 2000);

    setChartData(generateChartData());
    return () => clearInterval(interval);
  }, [generateChartData]);

  const timelineOptions = useMemo(() => ({
    backgroundColor: 'transparent',
    tooltip: {
      trigger: 'axis' as const,
      backgroundColor: 'rgba(26, 29, 62, 0.9)',
      borderColor: '#00d4ff',
      textStyle: { color: '#e6eef9' }
    },
    legend: {
      data: ['CPU', '内存', '网络入', '网络出'],
      textStyle: { color: '#9aa5b1' },
      top: 10
    },
    grid: {
      left: '3%',
      right: '4%',
      bottom: '3%',
      top: '15%',
      containLabel: true
    },
    xAxis: {
      type: 'category' as const,
      data: chartData.timestamps,
      axisLine: { lineStyle: { color: '#2a2f55' } },
      axisLabel: { color: '#9aa5b1' }
    },
    yAxis: {
      type: 'value' as const,
      axisLine: { lineStyle: { color: '#2a2f55' } },
      axisLabel: { color: '#9aa5b1' },
      splitLine: { lineStyle: { color: '#2a2f55' } }
    },
    series: [
      {
        name: 'CPU',
        type: 'line' as const,
        data: chartData.cpuData,
        lineStyle: { color: '#00d4ff', width: 2 },
        itemStyle: { color: '#00d4ff' },
        smooth: true
      },
      {
        name: '内存',
        type: 'line' as const,
        data: chartData.memoryData,
        lineStyle: { color: '#00ff88', width: 2 },
        itemStyle: { color: '#00ff88' },
        smooth: true
      },
      {
        name: '网络入',
        type: 'line' as const,
        data: chartData.networkInData,
        lineStyle: { color: '#ffb800', width: 2 },
        itemStyle: { color: '#ffb800' },
        smooth: true
      },
      {
        name: '网络出',
        type: 'line' as const,
        data: chartData.networkOutData,
        lineStyle: { color: '#ff4757', width: 2 },
        itemStyle: { color: '#ff4757' },
        smooth: true
      }
    ]
  }), [chartData]);

  const distributionOptions = useMemo(() => {
    const regionData = servers.reduce((acc, server) => {
      acc[server.region] = (acc[server.region] || 0) + 1;
      return acc;
    }, {} as Record<string, number>);

    return {
      backgroundColor: 'transparent',
      tooltip: {
        trigger: 'item' as const,
        backgroundColor: 'rgba(26, 29, 62, 0.9)',
        borderColor: '#00d4ff',
        textStyle: { color: '#e6eef9' }
      },
      legend: {
        orient: 'vertical' as const,
        left: 'left',
        textStyle: { color: '#9aa5b1' }
      },
      series: [
        {
          name: '服务器分布',
          type: 'pie' as const,
          radius: '50%',
          data: Object.entries(regionData).map(([name, value]) => ({
            name,
            value
          })),
          emphasis: {
            itemStyle: {
              shadowBlur: 10,
              shadowOffsetX: 0,
              shadowColor: 'rgba(0, 212, 255, 0.5)'
            }
          }
        }
      ]
    };
  }, [servers]);

  return (
    <div className="glass-effect rounded-lg p-6 h-full">
      <div className="flex items-center justify-between mb-4 flex-wrap gap-4">
        <h2 className="text-xl font-semibold text-text-primary">数据可视化中心</h2>

        <div className="flex items-center gap-4">
          <div className="flex items-center gap-2 bg-secondary-bg rounded-lg p-1">
            <button
              onClick={() => setViewMode('timeline')}
              className={`flex items-center gap-1 px-3 py-1 rounded text-sm transition-all ${
                viewMode === 'timeline'
                  ? 'bg-accent-blue text-primary-bg'
                  : 'text-text-secondary hover:text-text-primary'
              }`}
            >
              <Activity size={14} />
              时序
            </button>
            <button
              onClick={() => setViewMode('distribution')}
              className={`flex items-center gap-1 px-3 py-1 rounded text-sm transition-all ${
                viewMode === 'distribution'
                  ? 'bg-accent-blue text-primary-bg'
                  : 'text-text-secondary hover:text-text-primary'
              }`}
            >
              <PieChart size={14} />
              分布
            </button>
          </div>

          <select
            value={selectedDimension}
            onChange={(e) => setSelectedDimension(e.target.value as any)}
            className="bg-secondary-bg border border-border-color rounded-lg px-3 py-1 text-sm text-text-primary"
          >
            <option value="server">按服务器</option>
            <option value="region">按区域</option>
            <option value="service">按服务</option>
          </select>

          <select
            value={timeRange}
            onChange={(e) => setTimeRange(Number(e.target.value))}
            className="bg-secondary-bg border border-border-color rounded-lg px-3 py-1 text-sm text-text-primary"
          >
            <option value={5}>5分钟</option>
            <option value={10}>10分钟</option>
            <option value={15}>15分钟</option>
          </select>
        </div>
      </div>

      <div className="h-[calc(100%-60px)]">
        <ReactECharts
          key={viewMode}
          option={viewMode === 'timeline' ? timelineOptions : distributionOptions}
          style={{ height: '100%', width: '100%' }}
        />
      </div>
    </div>
  );
};